package Servlets;

import java.io.IOException;
import java.util.LinkedList;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import Corpus.Corpus;
import HTMLCrators.HTMLCreatorFromFileAndPairs;
import Main.Consts;
import Main.Pair;

public class ArticleServlet extends SuperServlet{

	private static final long serialVersionUID = 1L;
	private Corpus corpus;
	
	public ArticleServlet(Corpus corpus){
		this.corpus=corpus;
	}

	protected String[] fieldThatMustBe(){
		String[] ans={"id"}; 
		return ans;
	}

	protected void buildResponse(HttpServletRequest request,HttpServletResponse response) throws IOException {

		LinkedList<Pair<String, String>> pairs=new LinkedList<Pair<String,String>>();

		int id=fieldToInt(request, "id",-1);
		if (id>=0)
		{
			pairs.add(new Pair<String, String>("[ArticleId]", id+""));
			pairs.add(new Pair<String, String>("[URL]", Consts.SERVER_URI));
			String metadataName="";
			for(int i=0;i<corpus.getAllMetadataNames().size();i++)
				metadataName+=corpus.getAllMetadataNames().get(i).getFirst()+",";
			metadataName=metadataName.substring(0, metadataName.length()-1);
			pairs.add(new Pair<String, String>("[Metadata1]", "metadata=\""+metadataName+"\".split(\",\");"));
			
			String metadataRealName="";
			for(int i=0;i<corpus.getAllMetadataNames().size();i++)
				metadataRealName+=corpus.getAllMetadataNames().get(i).getSecend()+",";
			if (corpus.getAllMetadataNames().size()!=0)
				metadataRealName=metadataRealName.substring(0, metadataRealName.length()-1);
			pairs.add(new Pair<String, String>("[Metadata2]", "metadata2=\""+metadataRealName+"\".split(\",\");"));
			
			String metadataTypes="";
			for(int i=0;i<corpus.getAllMetadataNames().size();i++){
				metadataTypes+=corpus.getAllMetadataNames().get(i).getThird()+",";				
			}
			if (corpus.getAllMetadataNames().size()!=0)
				metadataTypes=metadataTypes.substring(0,metadataTypes.length()-1);
			pairs.add(new Pair<String, String>("[MetadataType]", "metadataType=\""+metadataTypes+"\".split(\",\");"));

			//String lang=corpus.getLanguage()==Language.English?"E":"H";
			
			HTMLCreatorFromFileAndPairs creator=new HTMLCreatorFromFileAndPairs("html\\showArticle"+"E"+".html", pairs);
			writeResponse(response, creator);
		}
		else{
			System.out.println("Error 8 ArticleServlet");//TODO Error 8 ArticleServlet
		}
	}

}